package com.ztgf.pay.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.trz.netwk.api.vo.PayRsut;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.pay.async.IAsyncService;
import com.ztgf.pay.common.service.IPayCommonService;
import com.ztgf.pay.mapper.PayOrderMapper;
import com.ztgf.pay.models.dto.PayOrderDTO;
import com.ztgf.pay.models.dto.PayUserDTO;
import com.ztgf.pay.models.service.IPayUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@DubboService
@Slf4j
public class PayCommonServiceImpl implements IPayCommonService {

    @Autowired
    private IAsyncService asyncService;
    @Resource
    private PayOrderMapper payOrderMapper;
    @Autowired
    private IPayUserService payUserService;

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void savePayBalanceResult(List<PayRsut> payRsutList,  Map<String, PayOrderDTO> orderDTOMap){

        for (PayRsut payRsut : payRsutList) {
//                    System.out.println("[orderno]=[" + payRsut.getOrderno() + "]"); // 业务单号
//                    System.out.println("[billno]=[" + payRsut.getBillno() + "]"); // 支付流水号(唯一)
//                    System.out.println("[platsrl]=[" + payRsut.getPlatsrl() + "]"); // 平台交易流水号
//                    System.out.println("[stat]=[" + payRsut.getStat() + "]"); // 订单状态:1成功;2失败
//                    System.out.println("[opion]=[" + payRsut.getOpion() + "]"); // 失败原因
            PayOrderDTO orderDTO = orderDTOMap.get(payRsut.getBillno());
            int status = 0;
            if("1".equals(payRsut.getStat())){
                status = 2;
                //处理不可提现金额
                saveNoWithdrawMoney(orderDTO.getPaymentUserId());
            } else {
                status = 3;
            }
            orderDTO.setStatus(status);
            PayOrderDTO newOrderDTO = new PayOrderDTO();
            newOrderDTO.setId(orderDTO.getId());
            newOrderDTO.setStatus(status);
            newOrderDTO.setNotifyStatus(1);
            newOrderDTO.setZjFailMsg(payRsut.getOpion());
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("id", orderDTO.getId());
            wrapper.eq("status", 0);
            Integer flag = payOrderMapper.update(newOrderDTO, wrapper);
            if(flag == null || flag != 1){
                throw new ServiceException(CodeEnum.FAIL_200022);
            }
            //TODO: 处理回调，事务提交后处理
            //修改payOrderLog 状态
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    try{
                        asyncService.notifyPayOrder(orderDTO);
                    } catch (ServiceException e) {
                        log.error("修改savePayOrderLogDTOStatus", e);
                    }
                }
            });

        }
    }

    @Override
    public void saveNoWithdrawMoney(Long userId){
        PayUserDTO userDTO = payUserService.getPayUserDTO(userId);
        if(userDTO == null){
            log.error(" saveNoWithdrawMoney userDTO is null" + userId);
            return;
        }
        //处理不可提现金额
        BigDecimal payMoney = payOrderMapper.getPayMoney(userDTO.getUserId(), userDTO.getNoWithdrawMoneySetTime());
        BigDecimal refundPayMoney = payOrderMapper.getRefundPayMoney(userDTO.getUserId(), userDTO.getNoWithdrawMoneySetTime());
        BigDecimal lastPayMoney = payMoney.subtract(refundPayMoney);
        BigDecimal noWithdrawMoney = BigDecimal.ZERO;
        if(lastPayMoney.compareTo(userDTO.getNoWithdrawMoneyInit()) < 0){
            noWithdrawMoney = userDTO.getNoWithdrawMoneyInit().subtract(lastPayMoney);
            if(noWithdrawMoney.compareTo(BigDecimal.ZERO) < 0){
                noWithdrawMoney = BigDecimal.ZERO;
            }
        }

        PayUserDTO newPayUserDTO = new PayUserDTO();
        int version = userDTO.getRevision();
        newPayUserDTO.setNoWithdrawMoney(noWithdrawMoney);
        newPayUserDTO.setRevision(version + 1);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", userDTO.getId());
        wrapper.eq("revision", version);
        if(!payUserService.update(newPayUserDTO, wrapper)){
            throw new ServiceException(CodeEnum.FAIL_200034);
        }
    }
}
